<!-- 页面路由配置 -->
<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '提油订单详情',
    navigationStyle: 'custom',
    disableScroll: true, // 微信禁止页面滚动
    'app-plus': {
      bounce: 'none', // 禁用 iOS 弹性效果
    },
  },
}
</route>

<!-- 页面模板 -->
<template>
  <PageLayout navTitle="提油订单详情" backRouteName="extractOrder" routeMethod="pushTab">
    <!-- 滚动区域 -->
    <scroll-view class="scrollArea" scroll-y>
      <!-- 表单容器 -->
      <view class="form-container">
        <wd-form ref="form" :model="formData">
          <wd-cell-group border:true>
            <wd-collapse v-model="collapseValue" collapse>
              <wd-collapse-item title="基本信息" name="item1">
                <!-- 工厂名称 -->
                <view class="form-item">
                  <wd-cell title="工厂名称">
                    <wd-select-picker
                      type="radio"
                      prop="materialType"
                      v-model="formData.factoryName"
                      :columns="factoryList"
                      :readonly="!isEditable"
                      :safe-area-inset-bottom="false"
                      :rules="[{ required: isEditable, message: '请选择原料类型' }]"
                    ></wd-select-picker>
                  </wd-cell>
                </view>

                <!-- 提油类型 -->
                <view class="form-item">
                  <wd-cell title="提油类型">
                    <wd-select-picker
                      type="radio"
                      prop="extractType"
                      v-model="formData.extractType"
                      :columns="extractTypes"
                      :readonly="!isEditable"
                      :safe-area-inset-bottom="false"
                      :rules="[{ required: isEditable, message: '请选择提油类型' }]"
                    ></wd-select-picker>
                  </wd-cell>
                </view>
                <!-- 提油方式 -->
                <view class="form-item">
                  <wd-cell title="提油方式">
                    <wd-select-picker
                      type="radio"
                      prop="extractMethod"
                      v-model="formData.extractMethod"
                      :columns="extractMethods"
                      :readonly="!isEditable"
                      :safe-area-inset-bottom="false"
                      :rules="[{ required: isEditable, message: '请选择提油方式' }]"
                    ></wd-select-picker>
                  </wd-cell>
                </view>
                <!-- 提油总量 -->
                <view class="form-item" v-if="formData.extractType === 'A'">
                  <wd-input
                    :label="`提油总量`"
                    label-width="120px"
                    prop="extractWeight"
                    v-model="extractWeight"
                    :readonly="true"
                    placeholder="用下方容器换算KG"
                    type="number"
                  >
                    <!-- <template #suffix>kg</template> -->
                  </wd-input>
                </view>
                <!-- 期望交货日期 -->
                <view class="form-item" v-if="formData.extractType === 'B'">
                  <wd-cell title="期望交货日期" title-width="120px">
                    <wd-calendar
                      :readonly="!isEditable"
                      prop="expectedDeliveryDate"
                      placeholder="请选择日期"
                      v-model="formData.expectedDeliveryDate"
                    />
                  </wd-cell>
                </view>
                <!-- 订单总金额 -->
                <view class="form-item" v-if="formData.extractType === 'B'">
                  <wd-input
                    :label="`订单总金额`"
                    label-width="120px"
                    prop="orderTotalAmount"
                    v-model="formData.orderTotalAmount"
                    :readonly="true"
                    placeholder="自动计算，所有商品加和"
                    type="number"
                  >
                    <!-- <template #suffix>kg</template> -->
                  </wd-input>
                </view>
                <!-- 订单状态 -->
                <view class="form-item">
                  <wd-cell title="订单状态">
                    <dictItem
                      dict-code="exchange_oil_order_status"
                      :value="formData.status"
                    ></dictItem>
                  </wd-cell>
                </view>
                <!-- 备注输入框 -->
                <view class="form-item">
                  <wd-textarea
                    label="备注"
                    label-width="100px"
                    prop="comments"
                    :readonly="!isEditable"
                    v-model="formData.comments"
                    :rules="[
                      { required: isEditable, max: 1000, message: '备注最多只能输入1000个字符' },
                    ]"
                    :maxlength="1000"
                    auto-height
                    placeholder="请输入备注"
                  ></wd-textarea>
                </view>
              </wd-collapse-item>
              <wd-collapse-item
                class="container-list"
                title="容器信息"
                name="item2"
                v-if="formData.extractType === 'A'"
              >
                <view class="list-header">
                  <view class="subtotal">总金额：{{ extractTotalAmount }}元</view>
                  <view>
                    <wd-button size="small" type="primary" icon="add" @click="addContainer">
                      添加容器
                    </wd-button>
                  </view>
                </view>
                <view class="container-item" v-for="item in formData.productContainerVos">
                  <!-- 是否自带容器 -->
                  <view class="form-item">
                    <wd-cell title="是否自带容器">
                      <wd-select-picker
                        type="radio"
                        prop="isByoContainer"
                        v-model="item.isByoContainer"
                        :columns="yesOrNo"
                        :readonly="!isEditable"
                        :safe-area-inset-bottom="false"
                        :rules="[{ required: isEditable, message: '请选择是否自带容器' }]"
                      ></wd-select-picker>
                    </wd-cell>
                  </view>
                  <!-- 选择容器 -->
                  <view class="form-item">
                    <wd-cell title="选择容器">
                      <wd-select-picker
                        type="radio"
                        prop="selectContainer"
                        v-model="item.selectContainer"
                        :columns="containerTypes"
                        :readonly="!isEditable"
                        :safe-area-inset-bottom="false"
                        :rules="[{ required: isEditable, message: '请选择提油方式' }]"
                      ></wd-select-picker>
                    </wd-cell>
                  </view>
                  <!-- 容器数量 -->
                  <view class="form-item">
                    <wd-input
                      label="容器数量"
                      v-model="item.containerNums"
                      type="number"
                      :readonly="!isEditable"
                      :min="0"
                    ></wd-input>
                  </view>
                  <!-- 单个容器罐装费 -->
                  <view class="form-item">
                    <wd-input
                      label="单个容器罐装费"
                      label-width="120px"
                      v-model="item.containerCost"
                      type="number"
                      :readonly="!isEditable"
                      :min="0"
                    >
                      <template #suffix>元</template>
                    </wd-input>
                  </view>
                  <!-- 费用小计 -->
                  <view class="form-item">
                    <wd-cell title="费用小计">
                      {{ item.containerCost * item.containerNums }} 元
                    </wd-cell>
                  </view>
                </view>
              </wd-collapse-item>
              <wd-collapse-item
                class="goods-list"
                title="商品信息"
                name="item2"
                v-if="formData.extractType === 'B'"
              >
                <view class="list-header">
                  <view class="subtotal">总金额：{{ extractGoodsAmount }}元</view>
                  <view>
                    <wd-button size="small" type="primary" icon="add" @click="addGoods">
                      新增商品
                    </wd-button>
                  </view>
                </view>
                <view class="goods-item" v-for="item in formData.productRecordVos">
                  <!-- 选择商品 -->
                  <view class="form-item">
                    <wd-cell title="选择商品">
                      <wd-select-picker
                        type="radio"
                        prop="goods"
                        v-model="item.goods"
                        :columns="productRecordVos"
                        :readonly="!isEditable"
                        :safe-area-inset-bottom="false"
                        :rules="[{ required: isEditable, message: '请选择商品' }]"
                      ></wd-select-picker>
                    </wd-cell>
                  </view>
                  <!-- 商品规格 -->
                  <view class="form-item">
                    <wd-cell title="商品规格">{{ item.spec }}</wd-cell>
                  </view>
                  <!-- 商品型号 -->
                  <view class="form-item">
                    <wd-cell title="商品型号">{{ item.model }}</wd-cell>
                  </view>
                  <!-- 商品单价 -->
                  <view class="form-item">
                    <wd-cell title="商品单价">{{ item.price }} 元</wd-cell>
                  </view>
                  <!-- 提油总量 -->
                  <view class="form-item">
                    <wd-input
                      label="提油总量"
                      v-model="item.extractNumber"
                      type="number"
                      :readonly="!isEditable"
                      :min="0"
                    ></wd-input>
                  </view>
                  <!-- 商品金额 -->
                  <view class="form-item">
                    <wd-cell title="商品金额">{{ item.extractNumber * item.price }}</wd-cell>
                  </view>
                </view>
              </wd-collapse-item>
              <wd-collapse-item title="收货信息" name="item3" v-if="formData.extractType === 'B'">
                <wd-cell is-link to="/pages/index/index">
                  <template #title>
                    <view>
                      <view>{{ formData.shouhuoren }}</view>
                      <view>{{ formData.shouhuorendianhua }}</view>
                    </view>
                    <view>{{ formData.shouhuodizhi }}</view>
                  </template>
                </wd-cell>
              </wd-collapse-item>
              <wd-collapse-item title="订单履历" name="item4" v-if="formData.status !== 'A'">
                <view class="order-history">
                  <wd-cell
                    v-for="(item, index) in formData.operationLogs"
                    :title="item.operationNode"
                    :key="index"
                  >
                    {{ item.createTime }}
                  </wd-cell>
                </view>
              </wd-collapse-item>
            </wd-collapse>
          </wd-cell-group>
        </wd-form>
      </view>
      <view class="konw-and-agree">
        <wd-checkbox
          v-if="isEditable"
          checked-color="#01b43f"
          v-model="formData.agreedToTerms"
          @change="handleknow"
        >
          已阅读并同意换油须知
        </wd-checkbox>
      </view>
    </scroll-view>

    <!-- 底部按钮区域 -->
    <view class="footer">
      <!-- 种植户按钮区域 -->
      <wd-button
        block
        type="info"
        @click="handleStaging"
        v-if="hasPermission('') && shouldShowButton('暂存')"
      >
        暂存
      </wd-button>
      <wd-button
        class="hold-form"
        block
        type="success"
        @click="deleteOrder"
        v-if="hasPermission('') && shouldShowButton('删除')"
      >
        删除
      </wd-button>
      <wd-button
        class="submit-form"
        block
        @click="handleSubmit"
        v-if="hasPermission('') && shouldShowButton('提交')"
      >
        提交并付款
      </wd-button>
      <wd-button
        class="hold-form"
        block
        type="success"
        @click="cancelOrder"
        v-if="hasPermission('') && shouldShowButton('取消订单')"
      >
        取消订单
      </wd-button>
      <!-- 待确认收货 -->
      <wd-button
        class="submit-form"
        block
        @click=""
        v-if="hasPermission('') && shouldShowButton('待确认收货')"
      >
        待确认收货
      </wd-button>
      <!-- 待确认自提 -->
      <wd-button
        class="submit-form"
        block
        @click=""
        v-if="hasPermission('') && shouldShowButton('待确认自提')"
      >
        待确认自提
      </wd-button>
      <!-- 确认收货 -->
      <wd-button
        class="submit-form"
        block
        @click=""
        v-if="hasPermission('') && shouldShowButton('确认收货')"
      >
        确认收货
      </wd-button>
    </view>
    <PaymentSelect ref="paymentSelectRef" @select="handlePaymentSelect" />
    <UploadPayProof ref="uploadPayProofRef" @upload="handleUploadPayProof" />
  </PageLayout>
</template>

<!-- 脚本部分 -->
<script lang="ts" setup>
import { useToast, useMessage, useNotify } from 'wot-design-uni'
import { useRouter } from '@/plugin/uni-mini-router'
import { useUserStore } from '@/store/user'
import { http } from '@/utils/http'
import { orderApi, userApi, payApi } from '@/api/api'
import { ref, reactive } from 'vue'
import { useLocationStore } from '@/store/location'
import { extractTypes, extractMethods, extractOrderStatus, yesOrNo } from '@/common/constants'
import { template } from 'lodash-es'
import dayjs from 'dayjs'
import { usePermission } from '@/hooks/usePermission'
import PaymentSelect from './components/paymentSelect.vue'
import UploadPayProof from './components/uploadPayProof.vue'
import { debounce } from 'lodash'

const message = useMessage()
const { hasPermission } = usePermission()

// 组件选项配置
defineOptions({
  name: 'ExtractCreateOrder',
  options: {
    styleIsolation: 'shared',
  },
})

// 计算属性
const extractWeight = computed(() => {
  if (!formData.productContainerVos || formData.productContainerVos.length === 0) return 0
  return formData.productContainerVos.reduce((sum, item) => {
    // return sum + (item.containerCost * item.containerNums);
    return sum + Number(item.containerNums)
  }, 0)
})

// 计算属性：计算容器总金额
const extractTotalAmount = computed(() => {
  if (!formData.productContainerVos || formData.productContainerVos.length === 0) return 0
  return formData.productContainerVos.reduce((sum, item) => {
    return sum + item.containerCost * item.containerNums
  }, 0)
})

// 计算属性：计算商品总金额
const extractGoodsAmount = computed(() => {
  if (!formData.productRecordVos || formData.productRecordVos.length === 0) return 0
  return formData.productRecordVos.reduce((sum, item) => {
    return sum + item.extractNumber * item.price
  }, 0)
})

// 初始化工具和状态
const toast = useToast()
const router = useRouter()
const userStore = useUserStore()
const locationStore = useLocationStore()
const value = ref<boolean>(true)
const orderId = ref<string>('')
const collapseValue = ref<string[]>(['item1', 'item2', 'item3', 'item4'])

const factoryList = ref([
  { label: '工厂A', value: 'factoryA' },
  { label: '工厂B', value: 'factoryB' },
  { label: '工厂C', value: 'factoryC' },
]) // 工厂列表
const containerTypes = ref([
  { label: '容器类型1', value: 'container1' },
  { label: '容器类型2', value: 'container2' },
  { label: '容器类型3', value: 'container3' },
]) // 容器类型列表
const productRecordVos = ref([
  { label: '商品A', value: 'goodsA' },
  { label: '商品B', value: 'goodsB' },
  { label: '商品C', value: 'goodsC' },
]) // 商品列表
const userRole = ref('') // 'factory' 或 'grower'

const paymentSelectRef = ref(null)
const uploadPayProofRef = ref(null)

// 计算属性：判断是否可编辑
const isEditable = computed(() => formData.status === 'A')

const userRoleId = userStore.userInfo.userRole
const userRoleName = userStore.userInfo.userRoleName
if (userRoleName && (userRoleName.includes('工厂') || userRoleName.includes('管理员'))) {
  userRole.value = 'factory'
} else {
  userRole.value = 'grows'
}
// 监听路由参数
onMounted(() => {
  orderId.value = router.route.value.params.orderId as string
  if (orderId.value) fetchOrderInfo()
  fetchFactoryList()
  fetchContainerTypes()
  fetchProductRecordVos()
})

// 添加容器
const addContainer = () => {
  console.log('addContainer')

  formData.productContainerVos.push({
    containerType: '',
    containerNums: '',
    containerCost: '',
  })
}

// 添加商品
const addGoods = (event) => {
  console.log('event', event)
  formData.productRecordVos.push({
    goods: '',
    spec: '',
    model: '',
    price: '5',
    extractNumber: '',
    productAmount: '',
  })
}

// 获取工厂列表
const fetchFactoryList = async () => {
  try {
    const res = await http.post(orderApi.getFactoryList, {})
    if (res.success) {
      factoryList.value = res.result
    } else {
      toast.error(res?.message || '获取工厂列表失败')
    }
  } catch (error) {
    toast.error('获取工厂列表失败')
  }
}

// 获取容器类型列表
const fetchContainerTypes = async () => {
  try {
    const res = await http.post(orderApi.getContainerTypes, {})
    if (res.success) {
      containerTypes.value = res.result
    } else {
      toast.error(res?.message || '获取容器类型列表失败')
    }
  } catch (error) {
    toast.error('获取容器类型列表失败')
  }
}
// 获取商品列表
const fetchProductRecordVos = async () => {
  try {
    const res = await http.post(orderApi.getGoodsList, {})
    if (res.success) {
      productRecordVos.value = res.result
    } else {
      toast.error(res?.message || '获取商品列表失败')
    }
  } catch (error) {
    toast.error('获取商品列表失败')
  }
}

// 表单数据
const formData = reactive({
  factoryName: '', // 工厂名称
  extractType: 'A', // 提油类型
  extractMethod: 'A', // 提油方式
  extractWeight: '', // 提油总量
  expectedDeliveryDate: '', // 期望交货日期
  orderTotalAmount: '', // 订单总金额
  status: 'A', // 订单状态
  comments: '', // 备注
  productContainerVos: [], // 容器信息列表
  productRecordVos: [], // 商品信息列表
  agreedToTerms: false, // 是否同意换油须知
  address: '', // 收货地址
  mob: '', // 手机号
  shouhuoren: '', // 收货人
  shouhuorendianhua: '', // 收货人电话
  shouhuodizhi: '', // 收货地址
  operationLogs: [], // 订单履历
})

// 质检结果
const qualityData = reactive({})

// 表单引用
const form = ref(null)

// 初始化时从store加载地址
if (locationStore.selectedLocation) {
  formData.address = locationStore.selectedLocation.address
}
// 监听位置变化
const unsubscribe = locationStore.$subscribe((mutation, state) => {
  if (state.selectedLocation) {
    formData.address = state.selectedLocation.address
  }
})

/**
 * 根据传入的状态判断是否显示某个模块
 * @param statusList
 */
const isShowItem = (statusList) => {
  return statusList.includes(formData.status)
}

// 获取订单信息
const fetchOrderInfo = async () => {
  try {
    // debugger
    const res = await http.post(orderApi.getOrderDetail, { id: orderId.value })
    Object.assign(formData, res.result)
    if (!formData.oilYield) {
      formData.oilYield = {
        teaCakeAdd: '',
        oilYield: '',
      }
    }
  } catch (error) {
    toast.error('获取订单信息失败')
  }
}

// 提交表单处理
const handleSubmit = debounce(
  async () => {
    uni.showModal({
      title: '确认',
      content: '确认提交订单？',
      success: async function (res) {
        if (res.confirm) {
          form.value
            .validate()
            .then(async ({ valid, errors }) => {
              if (valid) {
                if (formData.agreedToTerms !== true) {
                  toast.error('请阅读并同意《换油须知》')
                  return
                }
                console.log('表单校验通过，提交数据:', formData)
                const res = await http.post(orderApi.extractUpdateOrder, {
                  ...formData,
                  status: 'B',
                })
                if (res.success) {
                  toast.success('保存成功')
                  handleSuccess()
                } else {
                  toast.error(res?.message || '表单保存失败！')
                }
              }
            })
            .catch((error) => {
              console.error('表单校验失败:', error)
              uni.showToast({
                title: '请检查表单内容',
                icon: 'none',
              })
            })
        }
      },
    })
  },
  2000,
  { leading: true, trailing: false },
)

// 暂存表单处理
const handleStaging = debounce(
  async () => {
    const res = await http.post(orderApi.extractUpdateOrder, { ...formData, status: 'A' })
    if (res.success) {
      toast.success('暂存成功')
      fetchOrderInfo()
    } else {
      toast.error(res?.message || '暂存失败！')
    }
  },
  2000,
  { leading: true, trailing: false },
)

// 取消订单
const cancelOrder = debounce(
  async () => {
    uni.showModal({
      title: '取消',
      content: '确认取消订单？',
      success: async function (res) {
        if (res.confirm) {
          const res = await http.post(orderApi.cancelOrder, { id: orderId.value })
          if (res.success) {
            toast.success('取消成功')
            fetchOrderInfo()
          } else {
            toast.error(res?.message || '取消失败！')
          }
        }
      },
    })
  },
  2000,
  { leading: true, trailing: false },
)

// 手机号验证状态
const showPhoneTip = ref(false)

// 手机号验证方法
const validatePhone = (value) => {
  showPhoneTip.value = !/^\d+$/.test(value)
  return /^1[3-9]\d{9}$/.test(value)
}

// 打开《换油须知》文档
const openTermsDocument = () => {
  // 这里替换为实际文档的路径或链接
  uni.navigateTo({
    url: '/pages/documents/TermsOfService',
  })
  formData.agreedToTerms = true
}

// 获取微信手机号方法
const getPhoneNumber = async (e: any) => {
  try {
    // #ifdef MP-WEIXIN
    if (e.detail && e.detail.errMsg !== 'getPhoneNumber:ok') {
      throw new Error('用户拒绝了授权')
    }

    const [loginRes, phoneRes] = await Promise.all([
      new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin',
          success: resolve,
          fail: reject,
        })
      }),
      Promise.resolve(e.detail ? e.detail.code : null),
    ])

    const params = {
      code: phoneRes,
    }

    const res = await http.post(userApi.getUserPhoneByWx, params)

    if (res.success) {
      // 将获取到的手机号填入表单
      formData.mob = res.result as string
    } else {
      throw new Error(res.message || '获取手机号失败')
    }
    // #endif
    // #ifndef MP-WEIXIN
    // 非微信环境模拟数据
    console.log('现在使用的是非微信环境')
    formData.mob = '13272408547'
    // #endif
  } catch (err: any) {
    toast.warning(err.message || '获取手机号失败')
  }
}

// 跳转到地图选择页面
const goToLocationPage = () => {
  if (locationStore.selectedLocation) {
    locationStore.setTempLocation(locationStore.selectedLocation)
  }

  uni.navigateTo({
    url: '/pages-user/location/location',
  })
}

// 同意协议
const handleknow = (e) => {
  value.value = e.value
}

const handleSuccess = () => {
  setTimeout(() => {
    uni.$emit('refreshList')
    router.back()
  }, 1000)
}

// 删除订单
const deleteOrder = debounce(
  async () => {
    uni.showModal({
      title: '删除',
      content: '确认删除订单？',
      success: async function (res) {
        if (res.confirm) {
          try {
            const res = await http.post(orderApi.deleteOrder, { id: orderId.value })
            if (res.success) {
              toast.success('删除成功')
              handleSuccess()
            } else {
              toast.error(res?.message || '删除失败！')
            }
          } catch (error) {
            toast.error('删除失败')
          }
          // 在这里执行删除操作
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  },
  2000,
  { leading: true, trailing: false },
)

// 根据订单状态判断按钮是否需要显示
const shouldShowButton = (buttonName: string): boolean => {
  const status = formData.status
  // console.log(status, userRole.value)
  if (userRole.value === 'grows') {
    switch (status) {
      case 'A': // 待提交
        return ['暂存', '提交', '删除'].includes(buttonName)
      case 'B': // 待分配工厂
        return ['取消订单'].includes(buttonName)
      // case 'I': // 待确认质检
      //   return ['确认质检合格', '不合格退货'].includes(buttonName)
      case 'K': // 待确认得油结果
        return ['得油结果确认', '不认可得油结果'].includes(buttonName)
      case 'M': // 待付款
        return buttonName === '付款'
      default:
        return false
    }
  } else if (userRole.value === 'factory') {
    switch (status) {
      case 'C': // 待接单
        return ['同意', '拒绝'].includes(buttonName)
      case 'E': // 运输中
        return ['确认到货'].includes(buttonName)
      case 'H': // 待入库
        return ['补录入库数据'].includes(buttonName)
      case 'F': // 待质检
        return ['新增质检单', '修改质检单'].includes(buttonName)
      case 'I': // 待确认质检
        return ['删除此质检单', '确认质检合格', '不合格退货'].includes(buttonName)
      // case 'H': // 待入库
      //   return ['质检不认可', '已线下确认', '要求取消'].includes(buttonName)
      // case 'I': // 待确认质检
      //   return ['确认质检合格', '不合格退货'].includes(buttonName)
      case 'K':
        return buttonName === '确认得油'
      default:
        return false
    }
  } else {
    return false
  }
}

// 选择付款方式
const paymentSelect = () => {
  paymentSelectRef.value.open()
}

// 选择付款方式
const handlePaymentSelect = (type) => {
  console.log('type', type)
  if (type === 'wechat') {
    weixinPay()
  } else {
    uploadPayProofRef.value.open()
  }
}

async function weixinPay() {
  const res = await http.post(payApi.extractOrderPay, {
    orderId: orderId.value,
  })
  console.log('当前获得到的prepayid', res.result)
  const orderData = res.result
  // 订单对象，从服务器获取
  wx.requestPayment({
    timeStamp: orderData.timeStamp, // 时间戳字符串
    nonceStr: orderData.nonceStr, // 随机字符串
    package: orderData.packageValue, // 格式为 "prepay_id=xxx"
    signType: orderData.signType, // 签名算法类型
    paySign: orderData.paySign, // 签名值
    success: function (res) {
      getPayStatus(orderId.value)
    },
    fail: function (err) {
      /* 支付失败 */
      console.log(err)
    },
  })
}

async function getPayStatus(orderId) {
  const res = await http.post(payApi.getPayStatus, {
    orderId: orderId,
  })
  if (res.success) {
    console.log('当前获得到的支付状态', res.result)
    if (res.result === 'Y') {
      uni.showToast({
        title: '支付成功',
        icon: 'success',
        duration: 2000,
      })
      fetchOrderInfo()
    } else {
      toast.error('支付失败')
    }
  }
}

async function handleUploadPayProof(imageUrl) {
  const res = await http.post(payApi.uploadExtractOrderPayProof, {
    orderId: orderId.value,
    paymentProofImage: imageUrl,
  })
  if (res.success) {
    uni.showToast({
      title: '上传支付凭证成功',
      icon: 'success',
      duration: 2000,
    })
    fetchOrderInfo()
  } else {
    toast.error(res?.message || '上传支付凭证失败！')
  }
}

onUnmounted(() => {
  unsubscribe()
})

// 判断生产人员是否应显示“确认得油”按钮
const showProduceConfirm = computed(() => {
  return (
    userRole.value === 'factory' &&
    userRoleId === 'fac_produce_emp' &&
    formData.status === 'K' &&
    !formData.produceConfirm
  )
})

// 判断财务人员是否应显示“确认得油”按钮
const showFinanceConfirm = computed(() => {
  return (
    userRole.value === 'factory' &&
    userRoleId === 'fac_finance_emp' &&
    formData.status === 'K' &&
    formData.produceConfirm === 'Y' &&
    !formData.financeConfirm
  )
})

// 判断种植户是否应显示“得油结果确认”按钮
const showGrowerConfirm = computed(() => {
  return (
    userRole.value === 'grows' &&
    formData.status === 'K' &&
    formData.produceConfirm === 'Y' &&
    formData.financeConfirm === 'Y'
  )
})
</script>
<style lang="scss" scoped>
@import '@/style/custom/variables.scss';
.footer {
  padding: 10px 15px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 5px;
  :deep(.wd-button) {
    flex: 1;
  }
}
/* 添加获取手机号按钮样式 */
.custom-phone-button {
  // margin-left: 10px;
  // background: transparent; /* 透明背景 */
  display: inline-flex;
  padding: 0 8px; /* 内边距 */
  height: 28px; /* 高度匹配 wd-button */
  line-height: 28px;
  font-size: 12px; /* 字体大小 */
  color: #333; /* 文字颜色 */
  // border: 1px solid #ddd; /* 边框 */
  // border-radius: 4px; /* 圆角 */
}

/* 如果需要 hover 效果 */
.custom-phone-button:hover {
  opacity: 0.8;
}

// 统一样式
.form-container {
  background: none;
  padding: var(--wot-card-padding, 0 var(--wot-size-side-padding, 15px));
  :deep(.wd-cell__wrapper) {
    padding: 5px 0;
    border-bottom: 1px solid #bbbbbb;
  }

  :deep(.wd-select-picker__cell) {
    padding: 0;
  }
  :deep(.wd-collapse-item__body) {
    background: #f3f3f3;
    border-radius: 16px;
  }
  .container-list,
  .goods-list {
    .list-header {
      display: flex;
      justify-content: space-between;
      padding: 0 15px;
      font-size: 14px;
      align-items: center;
      color: #0710f1;
    }
    :deep(.wd-collapse-item__body) {
      background: #ffffff;
      border-radius: 16px;
    }
  }
  .container-item,
  .goods-item {
    background: #f3f3f3;
    border-radius: 16px;
    padding: 10px 10px 10px 0;
    margin: 10px 0;
  }

  .form-item {
    // margin: 30upx 20upx;
    // box-shadow: 0 2upx 20upx #000;
    // border-radius: 20upx;
    // border: 4upx solid $primary-color; // 使用 SCSS 变量
    overflow: hidden;
    :deep(.wd-input),
    :deep(.wd-textarea),
    :deep(.wd-textarea__value) {
      background: none;
    }
    :deep(.wd-cell) {
      background: none;
    }
    :deep(.wd-input) {
      margin: 5px 0 5px var(--wot-input-padding, var(--wot-size-side-padding, 15px));
      padding: 0;
      border-bottom: 1px solid #bbbbbb;
    }
    :deep(.wd-calendar__cell) {
      padding: 0;
      background: none;
    }
    :deep(.wd-select-picker__cell) {
      background: none;
    }
    :deep(.wd-input__body) {
      text-align: right;
    }
    :deep(.wd-select-picker__body) {
      text-align: right;
    }
    :deep(.wd-textarea__value) {
      text-align: right;
    }
  }
}
:deep(.wd-cell-group__body) {
  background: none;
}
:deep(.wd-textarea) {
  // margin: 30upx 20upx;
  border-radius: 30upx;
  // background: none;
}

.footer {
  margin-bottom: 50upx;
}

.footer:deep(.wd-button) {
  border-radius: 40upx !important;
}
.submit-form {
  background: $primary-color !important; // 使用 SCSS 变量
}
.hold-form {
  background: #333333 !important;
}

.konw-and-agree {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 20px;
  // color: $primary-color; // 使用 SCSS 变量
  :deep(.wd-checkbox__txt) {
    color: $primary-color; // 使用 SCSS 变量
  }
}

.quality-item {
  :deep(.wd-card) {
    margin: 0;
    padding: 0;
  }
  .form-item {
    padding-right: 10px;
  }
  .quality-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .quality-btns {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 5px;
    }
  }
  .form-item {
    :deep(.wd-cell__title) {
      font-size: 12px;
    }
    :deep(.wd-cell__body) {
      font-size: 12px;
    }
  }
  .confirmStatus0 {
    border-radius: 4px;
    background: #1ea262;
    color: #fff;
    display: inline-block;
    padding: 0 5px;
  }
  .confirmStatus1 {
    border-radius: 4px;
    background: #f20b0b;
    color: #fff;
    display: inline-block;
    padding: 0 5px;
  }
  .confirmStatus2 {
    border-radius: 4px;
    background: #1373e4;
    color: #fff;
    display: inline-block;
    padding: 0 5px;
  }
  .confirmStatus3 {
    border-radius: 4px;
    background: #fdd143;
    color: #d54213;
    display: inline-block;
    padding: 0 5px;
  }
  .qulity-btns {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 5px;
  }
  .qulity-confirmation {
    border-radius: 4px;
    background: #ed691f;
    color: #ffffff;
    display: inline-block;
    padding: 0 5px;
  }
  .qulity-returned {
    border-radius: 4px;
    background: #d5d5d5;
    color: #000000;
    display: inline-block;
    padding: 0 5px;
  }
  .qulity-unqualified {
    border-radius: 4px;
    background: #101010;
    color: #ffffff;
    display: inline-block;
    padding: 0 5px;
  }
}
.order-history {
  :deep(.wd-cell) {
    background: none;
  }
}
.collapse-item-title {
  display: flex;
  width: 100%;
  justify-content: space-between;
  align-items: center;
  .left {
    display: flex;
    align-items: center;
    gap: 10px;
    color: var(--wot-collapse-title-color, rgba(0, 0, 0, 0.85));
    font-weight: var(--wot-fw-medium, 500);
    font-size: var(--wot-collapse-title-fs, 16px);
    .subtotal {
      color: #0710f1;
      font-size: 12px;
    }
  }
}
</style>
